package by.grsu.kononovich.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.kononovich.entity.Client;
import by.grsu.kononovich.table.ClientTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class ClientDao extends AbstractDao<ClientTable, Client> {

	public ClientDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Client newClient) {
		newClient.setId(getNextId());
		final ClientTable clientTable = deserializeFromXml();
		clientTable.getRows().add(newClient);
		serializeToXml(clientTable);
	}

	@Override
	public void update(final Client entity) {
		final ClientTable clientTable = deserializeFromXml();
		for (final Client row : clientTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				row.setName(entity.getName());
				row.setSurName(entity.getSurname());
				row.setPasport(entity.getPasport());
				break;
			}
		}
		serializeToXml(clientTable);
	}

	@Override
	public Client get(final Serializable id) {
		final ClientTable clientTable = deserializeFromXml();
		for (final Client row : clientTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Client> getAll() {
		final ClientTable clientTable = deserializeFromXml();
		return clientTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		final ClientTable clientTable = deserializeFromXml();
		Client toBeDeleted = null;
		for (final Client row : clientTable.getRows()) {
			if (row.getId().equals(id)) {
				toBeDeleted = row;
				break;
			}
		}
		clientTable.getRows().remove(toBeDeleted);
		serializeToXml(clientTable);
	}

	@Override
	protected Class<ClientTable> getTableClass() {
		return ClientTable.class;
	}

}
